package com.sunlake.spring.main.common.model.file.controller;

import com.sunlake.spring.main.common.model.file.service.impl.ResumeDownloadServiceImpl;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 文件下载Controller
 * 提供上传文件的访问和下载功能
 */
@RestController
@RequestMapping("/api/file/download")
public class FileDownloadController {

    @Autowired
    ResumeDownloadServiceImpl fileDownloadService;

        // ============== 下载相关 ==============
    /**
     * 获取文件元信息（用于探测是否支持断点续传、总大小、类型、建议文件名）
     * 注意：此接口直接返回原始 JSON（非 R 包裹），以便前端直接读取字段
     */
    @PostMapping(value = "/meta", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Map<String, Object> getFileMeta(@RequestBody Map<String, Object> body) {
        Object idObj = body != null ? body.get("fileId") : null;
        Long fileId = null;
        if (idObj instanceof Number) {
            fileId = ((Number) idObj).longValue();
        } else if (idObj instanceof String) {
            try { fileId = Long.parseLong((String) idObj); } catch (Exception ignored) {}
        }
        if (fileId == null) {
            Map<String, Object> err = new HashMap<>();
            err.put("acceptRanges", false);
            err.put("totalSize", null);
            return err;
        }
        return fileDownloadService.getFileMeta(fileId);
    }

    /**
     * 整文件下载（POST + blob）
     */
    @PostMapping("/{fileId}")
    public void downloadFile(@PathVariable("fileId") Long fileId, HttpServletResponse response) throws IOException {
        fileDownloadService.downloadFile(fileId, response);
    }

    /**
     * 范围下载（断点续传）
     * 支持从请求体中读取 { start, end }，也兼容 X-Range: bytes=start-end
     */
    @PostMapping("/{fileId}/download-range")
    public void downloadFileRange(
            @PathVariable("fileId") Long fileId,
            @RequestHeader(value = "X-Range", required = false) String xRange,
            @RequestBody(required = false) Map<String, Object> body,
            HttpServletResponse response) throws IOException {
        long start = 0L;
        long end = -1L;
        if (body != null) {
            Object s = body.get("start");
            Object e = body.get("end");
            if (s instanceof Number) start = ((Number) s).longValue();
            if (e instanceof Number) end = ((Number) e).longValue();
        }
        if (end < 0 && xRange != null && xRange.startsWith("bytes=")) {
            // 解析形如 bytes=0-1023
            try {
                String range = xRange.substring(6);
                String[] parts = range.split("-");
                if (parts.length == 2) {
                    start = Long.parseLong(parts[0].trim());
                    end = Long.parseLong(parts[1].trim());
                }
            } catch (Exception ignored) {}
        }
        fileDownloadService.downloadFileRange(fileId, start, end, response);
    }

}